package cn.dugcrs.user.service.impl;

import cn.dugcrs.basic.constant.BaseConstants;
import cn.dugcrs.basic.dto.RegisterDto;
import cn.dugcrs.basic.exception.BusinessException;
import cn.dugcrs.basic.utils.MD5Utils;
import cn.dugcrs.basic.utils.StrUtils;
import cn.dugcrs.user.domain.Logininfo;
import cn.dugcrs.user.domain.User;
import cn.dugcrs.user.mapper.LogininfoMapper;
import cn.dugcrs.user.mapper.UserMapper;
import cn.dugcrs.user.service.IUserService;
import cn.dugcrs.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gubcog
 * @since 2022-05-08
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
     * 根据手机号查找用户
     * @param phone
     * @return
     */
    @Override
    public User loadByPhone(String phone) {
        return userMapper.loadByPhone(phone);
    }


    /**
     * 根据邮箱查找用户
     * @param email
     * @return
     */
    @Override
    public User loadByEmail(String email) {
        return userMapper.loadByEmail(email);
    }

    /**
     * 用户注册
     * @param dto
     */
    @Override
    @Transactional
    public void phoneRegister(RegisterDto dto) {
        String phone = dto.getPhone();
        String smscode = dto.getSmscode();
        String password = dto.getPassword();
        String confirmpassword = dto.getConfirmpassword();
        // 空校验
        if (phone == null
                || smscode == null
                || password == null
                || confirmpassword == null) {
            throw new BusinessException("参数不能为空！！！");
        }
        // 判断原来的验证码是否有效
        String key = BaseConstants.SmsCodeConstants.BUSINESS_REGISTER_PREFIX + phone;
        Object smsCodeTmp = redisTemplate.opsForValue().get(key);
        String smsCodeTmps = smsCodeTmp.toString().split(":")[0];
        if(smsCodeTmps == null ){
            throw new BusinessException("无效的手机验证码或过期，请重新输入");
        }
        System.out.println(smsCodeTmp.toString());
        if(!smscode.equalsIgnoreCase(smsCodeTmps)){
            throw new BusinessException("错误的手机验证码，请重新输入");
        }

        // 校验手机号是否被注册
        User user = userMapper.loadByPhone(dto.getPhone());
        if (user != null) {
            throw new BusinessException("该手机号已经注册。请直接登录！");
        }

        System.out.println("成功");

        // 保存数据 t_user + t_logininfo
        User users = dto2User(dto);
        Logininfo logininfo = user2Logininfo(users);
        logininfoMapper.save(logininfo);
        users.setLogininfoId(logininfo.getId());
        userMapper.save(users);

    }


    /**
     * 邮箱用户注册
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public void emailRegister(RegisterDto dto) {
        String email = dto.getEmail();
        String smscode = dto.getSmscode();
        String password = dto.getPassword();
        String confirmpassword = dto.getConfirmpassword();
        // 空校验
        if (email == null
                || smscode == null
                || password == null
                || confirmpassword == null) {
            throw new BusinessException("参数不能为空！！！");
        }
        // 判断原来的验证码是否有效
        String key = BaseConstants.SmsCodeConstants.BUSINESS_REGISTER_PREFIX + email;
        Object smsCodeTmp = redisTemplate.opsForValue().get(key);
        String smsCodeTmps = smsCodeTmp.toString().split(":")[0];
        if(smsCodeTmps == null ){
            throw new BusinessException("无效的邮箱验证码或过期，请重新输入");
        }
        System.out.println(smsCodeTmp.toString());
        if(!smscode.equalsIgnoreCase(smsCodeTmps)){
            throw new BusinessException("错误的邮箱验证码，请重新输入");
        }

        // 校验邮箱是否被注册
        User user = userMapper.loadByPhone(dto.getPhone());
        if (user != null) {
            throw new BusinessException("该邮箱已经注册。请直接登录！");
        }


        // 保存数据 t_user + t_logininfo
        User users = dto2User(dto);
        Logininfo logininfo = user2Logininfo(users);
        logininfoMapper.save(logininfo);
        users.setLogininfoId(logininfo.getId());
        userMapper.save(users);
    }


    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        // 设置账号为普通用户
        logininfo.setType(1);
        return logininfo;
    }

    private User dto2User(RegisterDto dto) {
        User user = new User();
        if (dto.getPhone() != null) {
            user.setUsername(dto.getPhone());
        } else {
            user.setUsername(dto.getEmail());
        }
        user.setPhone(dto.getPhone());
        user.setEmail(dto.getEmail());
        String salt = StrUtils.getComplexRandomString(32);
        String md5pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5pwd);
        return user;
    }

    /**
     * 重写删除，级联删除
     * t_user + t_logininfo
     * @param id
     */
    @Override
    @Transactional
    public void remove(Long id) {
        User user = userMapper.loadById(id);
        userMapper.remove(id);
        logininfoMapper.remove(user.getLogininfoId());
    }

    /**
     * 重写修改，级联修改
     * t_user + t_logininfo
     * @param user
     */
    @Override
    @Transactional
    public void update(User user) {
        userMapper.update(user);
        Logininfo logininfo = user2Logininfo(user);
        logininfo.setId(user.getLogininfoId());
        logininfoMapper.update(logininfo);
    }
}
